import EmptyXML from '@/components/design/utils/EmptyXML';
import { EditorSettings } from 'types/editor/settings';
import modelerStore from '@/store/modules/modeler';
import {
  addEventListener,
} from '@/components/design/bo-utils/executionListenersUtil';


export const createNewDiagram = async function (newXml?: string, settings?: EditorSettings) {
  try {
    const store = modelerStore();
    const timestamp = Date.now();
    const { processId, processName, processEngine } = settings || {};
    console.log(settings,"settings1111")
    const newId: string = processId ? processId : `Process_${timestamp}`;
    const newName: string = processName || `业务流程_${timestamp}`;
    const startEventId="Event_"+generateRandomString();
    const endEventId="Event_"+generateRandomString();
    const sequenceFlowId="Flow_"+generateRandomString();
    const activityId="Activity_"+generateRandomString();
    const terminateEventDefinitionId="TerminateEventDefinitionId_"+generateRandomString();
    const taskParams="${"+activityId+"}";
    const xmlString = newXml || EmptyXML(newId, newName, processEngine,startEventId,endEventId,sequenceFlowId,activityId,taskParams,terminateEventDefinitionId);
    //const modeler = store.getModeler;
    const modeler = modelerStore();
    const { warnings } = await modeler.getModeler!.importXML(xmlString);
    let activatedElement = modeler.getElRegistry?.find((el) => el.type === 'bpmn:Process');
    //const activeListener = activatedElement.businessObject.extensionElements;
    //if (!activeListener) {      
    const newListener = { events: 'CUSTOM', class: 'com.zsix.system.service.listener.ProcessEventListener' };
    addEventListener(activatedElement, newListener);
    

    //}
    if (warnings && warnings.length) {
      warnings.forEach((warn) => console.warn(warn));
    }
  } catch (e) {
    console.error(`[Process Designer Warn]: ${typeof e === 'string' ? e : (e as Error)?.message}`);
  }
};
export const generateRandomChar=()=> {
  const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
  const randomIndex = Math.floor(Math.random() * characters.length);
  return characters[randomIndex];
};
export const generateRandomString=()=> {
  let result = '';
  for (let i = 0; i < 6; i++) {
    result += generateRandomChar();
  }
  return result;
};
